import base64
import os
import subprocess
import json
# import wmi
import hashlib
import json
import os
from datetime import datetime, timedelta

import ctypes
import asyncio
import platform
import traceback
from pathlib import Path
from mitmproxy import http, options
from mitmproxy.net.server_spec import ServerSpec
from mitmproxy.tools.dump import DumpMaster
from mitmproxy.tools.main import mitmdump

from proxy_manager import ProxyManager

CONFIG_FILE_PATH = "config.json"
# 配置常量
CA_CERT_NAME = "mitmproxy-ca-cert.cer"

# 店小秘
DXM_AUTH_URL = "https://www.dianxiaomi.com/api/userInfo.json"

# TEMU 处理
TEMU_HOST = "https://seller.kuajingmaihuo.com"
TEMU_QUAN_TUO_AUTH_URL = "https://seller.kuajingmaihuo.com/bg/quiet/api/mms/userInfo"

# TEMU 半托认证url
TEMU_BANTUO_AUTH_URL = "https://www.dianxiaomi.com/shop/list/pddkj.htm"
# TEMU_BANTUO_AUTH_URL = "https://agentseller.temu.com/api/seller/auth/userInfo"

# shein 半托认证url
SHEIN_BANTUO_AUTH_URL = "https://www.dianxiaomi.com/sheinProduct/add.htm"

PROXY_PORT = 18888

# 代理信息
proxy_ip = "127.0.0.1"
proxy_port = 7890
proxy_username = ""
proxy_password = ""


# proxy_ip = "168.158.59.42"
# proxy_port = 44445
# proxy_username = "14afbec1061be"
# proxy_password = "7e458caded"


class SystemProxyManager:
    """Windows系统代理管理工具"""
    REG_PATH = r"Software\Microsoft\Windows\CurrentVersion\Internet Settings"

    def __init__(self):

        self.original_settings = {}
        self.save_original_settings()

    def save_original_settings(self):
        """保存原始代理设置"""
        try:
            import winreg
            key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, self.REG_PATH)
            self.original_settings["ProxyEnable"] = winreg.QueryValueEx(key, "ProxyEnable")[0]
            self.original_settings["ProxyServer"] = winreg.QueryValueEx(key, "ProxyServer")[0]
            winreg.CloseKey(key)
        except FileNotFoundError:
            self.original_settings = {"ProxyEnable": 0, "ProxyServer": ""}

    def set_proxy(self, enable=True):
        """配置系统代理（带错误重试）"""
        try:
            import winreg
            key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, self.REG_PATH, 0, winreg.KEY_WRITE)
            if enable:
                winreg.SetValueEx(key, "ProxyEnable", 0, winreg.REG_DWORD, 1)
                winreg.SetValueEx(key, "ProxyServer", 0, winreg.REG_SZ, f"127.0.0.1:{PROXY_PORT}")
            else:
                # 恢复原始设置时优先使用保存的值，否则使用默认值
                winreg.SetValueEx(key, "ProxyEnable", 0, winreg.REG_DWORD,
                                 self.original_settings.get("ProxyEnable", 0))
                winreg.SetValueEx(key, "ProxyServer", 0, winreg.REG_SZ,
                                 self.original_settings.get("ProxyServer", ""))
            winreg.CloseKey(key)
            self.refresh_settings()
            return True
        except Exception as e:
            print(f"❌ 代理设置失败: {str(e)}")
            return False
        # return True

    def refresh_settings(self):
        """刷新系统设置使代理生效"""
        try:
            INTERNET_OPTION_REFRESH = 37
            internet_set_option = ctypes.windll.Wininet.InternetSetOptionW
            internet_set_option(0, INTERNET_OPTION_REFRESH, 0, 0)
        except Exception as e:
            print(f"⚠️ 刷新设置失败: {str(e)}")


class CertificateInstaller:
    """CA证书安装工具（修复证书生成逻辑）"""

    @staticmethod
    def install_windows_ca():
        """自动安装CA证书到Windows系统信任存储区"""
        cert_dir = Path.home() / ".mitmproxy"
        print(f"📦 CA证书目录: {cert_dir}")
        cert_path = cert_dir / CA_CERT_NAME

        # ✅ 修复点：确保证书目录存在
        cert_dir.mkdir(parents=True, exist_ok=True)

        # ✅ 修复点：正确生成证书（避免路径错误）
        if not cert_path.exists():
            print("⚠️ 证书不存在，正在生成...")
            try:
                # 显式生成证书到目标目录
                mitmdump(args=["-q", "--set", f"confdir={cert_dir}"])
                print("✅ 证书生成成功")
            except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
                print(f"❌ 证书生成失败: {str(e)}")
                return False

        # ✅ 安装证书（带路径验证）
        try:
            if not cert_path.exists():
                raise FileNotFoundError(f"证书文件不存在: {cert_path}")

            install_cmd = f'certutil -addstore -f "Root" "{cert_path}"'
            subprocess.run(install_cmd, shell=True, check=True)
            print(f"🔒 证书已安装: {cert_path}")
            return True
        except (subprocess.CalledProcessError, FileNotFoundError) as e:
            print(f"❌ 证书安装失败: {e}")
            return False


# 自定义上下文标识符
TEMU_SELF_HEADER_FLAG = "anti-content"



# def generate_device_fingerprint():
#     """生成设备唯一指纹（基于主板和硬盘序列号）"""
#     try:
#         c = wmi.WMI()
#         # 获取主板序列号
#         motherboard = next((s.SerialNumber.strip() for s in c.Win32_BaseBoard()), None)
#         # 获取硬盘序列号
#         disk = next((d.SerialNumber.strip() for d in c.Win32_DiskDrive()), None)
#
#         if motherboard and disk:
#             # 组合生成设备指纹
#             raw_fingerprint = f"{motherboard}_{disk}".encode()
#             return hashlib.sha256(raw_fingerprint).hexdigest()
#         return None
#     except Exception as e:
#         print(f"⚠️ 设备指纹生成失败: {str(e)}")
#         return None


def check_authorization():
    """验证授权文件有效性"""
    try:
        with open("授权文件.txt", "r", encoding="utf-8") as f:
            data = json.load(f)

        # 验证文件格式
        if not all(key in data for key in ["license_key", "activation_time"]):
            print("❌ 授权文件格式错误")
            return False

        # 解析授权码
        license_key = data["license_key"]
        if not license_key.startswith("DXM_"):
            print("❌ 非法授权码格式")
            return False

        # 提取有效期信息
        parts = license_key.split("_")
        if len(parts) != 3:
            print("❌ 授权码格式错误")
            return False

        # 验证签名（使用预共享密钥）
        secret_key = b"dxm_proxy_auth_key_2023"
        expected_signature = parts[2]

        payload = f"{parts[1]}|{data['expiration_days']}".encode()
        actual_signature = hashlib.sha256(secret_key + payload).hexdigest()[:16]

        if expected_signature != actual_signature:
            print("❌ 授权码无效")
            return False

        # 验证有效期
        activation_time = datetime.fromisoformat(data["activation_time"])
        expiration_time = activation_time + timedelta(days=data['expiration_days'])
        if datetime.now() > expiration_time:
            print(f"❌ 授权已过期（有效期至{expiration_time.strftime('%Y-%m-%d')}）")
            return False

        print(f"✅ 授权验证成功，有效期至{expiration_time.strftime('%Y-%m-%d')}）")
        return True

    except FileNotFoundError:
        print("❌ 授权文件未找到")
        return False
    except json.JSONDecodeError:
        print("❌ 授权文件格式错误")
        return False
    except Exception as e:
        print(f"❌ 授权验证失败: {str(e)}")
        return False


async def start_mitmproxy():
    """启动mitmproxy代理服务器"""
    config = options.Options(
        listen_host="127.0.0.1",
        listen_port=PROXY_PORT,
        ssl_insecure=True,
        upstream_cert=False,
        # mode=["socks5"]
        # mode=["upstream:http://127.0.0.1:7890"]

    )
    addons = [JsonModifier()]

    print(f"\n🔁 代理服务已启动 | 端口: {PROXY_PORT}")
    print("=" * 50)
    print("操作说明:")
    print("- 所有HTTP/HTTPS流量已通过本代理")
    print("- 按 Ctrl+C 退出程序并恢复设置")
    print("=" * 50)

    master = DumpMaster(config)
    master.addons.add(*addons)
    await master.run()


def main():
    # 判断是否为Windows系统
    if platform.system() == "Windows":
        print("✅ 当前系统是Windows")

        # 检查授权状态
        if not check_authorization():
            print("❌ 未通过授权验证，程序终止")
            input("按Enter键退出...")
            exit(1)

        # 检查管理员权限
        if ctypes.windll.shell32.IsUserAnAdmin() == 0:
            print("❌ 请以管理员身份运行此程序！")
            input("按Enter键退出...")
            exit(1)

        # 初始化代理管理器
        proxy_manager = SystemProxyManager()
        restore_proxy = False

        try:
            # 安装CA证书
            print("\n🔐 正在安装CA证书...")
            if CertificateInstaller.install_windows_ca():
                print("✅ CA证书安装成功")

                # 设置系统代理
                if proxy_manager.set_proxy(enable=True):
                    print(f"🌐 系统代理已设置: 127.0.0.1:{PROXY_PORT}")
                    restore_proxy = True

                    # 启动代理
                    asyncio.run(start_mitmproxy())
            else:
                print("程序终止：证书安装失败")
        except KeyboardInterrupt:
            print("\n🛑 用户中断操作")
        except Exception as e:
            print(f"🔥 未捕获的异常: {str(e)}")
            traceback.print_exc()
        finally:
            # 确保恢复代理设置
            if restore_proxy:
                try:
                    proxy_manager.set_proxy(enable=False)
                    print("✅ 系统代理已恢复")
                except Exception as e:
                    print(f"⚠️ 代理恢复警告: {str(e)}")
    else:
        print(f"❌ 当前系统不是Windows，请手动设置代理，端口为:{PROXY_PORT}")
        # 启动代理
        asyncio.run(start_mitmproxy())


if __name__ == "__main__":
    # JsonModifier().test()
    main()
